const config = require('./router.config.json');
const argsConfig = require('./args.config.json');
const _ = require('lodash');
const genSwaggerJsDoc = require('./swagger');

function getTypeofArgs(type) {
  // null 类型是 object, undefined 类型是 undefined
  if (!type || type === undefined || type === '') return null;
  return type;
}

function isRequired(args) {
  return args['必填'] === '必填';
}

function getRequiredArgs(argsList) {
  return argsList.filter((obj) => isRequired(obj));
}

function getReqArgs(method, argsList) {
  let parentNode = null;
  if (method === 'post') parentNode = 'body';
  else if (method === 'get') parentNode = 'query';
  else throw new Error('仅支持 get/post 传参');
  return argsList.filter((obj) => obj['父节点'] === parentNode);
}

module.exports = function () {
  let routerIndexModels = [];
  let routerModels = [];
  let serviceModels = [];
  let allArgsModels = [];
  const modules = config.modules;
  const publicRoute = config.publicRoute;

  for (const moduleObj of modules) {
    let routersInIndex = [];
    const baseUrl = moduleObj.baseUrl;
    const routers = moduleObj.routers;
    for (const router of routers) {
      const name = router.name;
      const method = router.method;
      const url = router.url;
      const allArgs = getReqArgs(method, argsConfig[name].argsList);
      const checkArgs = getRequiredArgs(allArgs);
      routerModels.push({
        baseUrl,
        url,
        name,
        method,
        args: allArgs.map(
          (obj) =>
            `req.${obj['父节点']}.${obj['参数名']}, // ${obj['必填']} ${obj['描述']}`
        ),
        checkArgs: checkArgs.map((obj) => `'${obj['参数名']}'`).join(', '),
      });
      serviceModels.push({
        baseUrl,
        name,
        args: allArgs.map(
          (obj) => `${obj['参数名']}, // ${obj['必填']} ${obj['描述']}`
        ),
      });
      routersInIndex.push({
        url,
        name,
      });

      // 参数校验
      let newArgsList = [];
      for (const args of allArgs) {
        newArgsList.push({
          name: args['参数名'],
          required: isRequired(args),
          typeof: getTypeofArgs(args['类型']),
          regex: args['正则'],
        });
      }
      allArgsModels.push({
        name,
        argsList: newArgsList,
      });
    }
    routerIndexModels.push({
      baseUrl,
      routersInIndex,
    });
  }
  const apiModel = {
    allArgsModels: { allArgsModels },
    routerModels,
    serviceModels,
    routerIndexModels,
    indexModel: {
      publicRoute,
      moduleRouters: modules.map((obj) => obj.baseUrl),
    },
    swaggerModel: {
      swaggerJsDoc: genSwaggerJsDoc() || '',
    },
  };
  return apiModel;
};
